package com.zara.store.server;

import java.io.IOException;

import javax.ejb.ActivationConfigProperty;
import javax.ejb.CreateException;
import javax.ejb.EJB;
import javax.ejb.EJBException;
import javax.ejb.MessageDriven;
import javax.ejb.MessageDrivenBean;
import javax.ejb.MessageDrivenContext;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
import javax.xml.transform.TransformerException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.zara.store.common.EnvtHelper;
import com.zara.store.common.EnvtVO;
import com.zara.store.common.IntegrationTransformer;

@MessageDriven(activationConfig = {
		@ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue"),
		@ActivationConfigProperty(propertyName = "destination", propertyValue = "queue/envt") })
public class EnvtMessageDrivenBean implements MessageDrivenBean,
		MessageListener {

	public void onMessage(Message message) {
		if (message != null && message instanceof TextMessage) {
			Log log = LogFactory.getLog(EnvtMessageDrivenBean.class); 
			EnvtVO ofad;
			try {
				String xml = ((TextMessage) message).getText();
				String xmlVO = new IntegrationTransformer()
						.transform(xml);
				ofad = new EnvtHelper().createEnvtFromXml(xmlVO);
				processBusiness.createEnvt(ofad);
			} catch (JMSException e) {
				e.printStackTrace();
				log.info("Ofad: JMSException", e);
			} catch (TransformerException e) {
				e.printStackTrace();
				log.info("Ofad: TransformerException", e);
			} catch (IOException e) {
				e.printStackTrace();
				log.info("Ofad: IOException", e);
			}
		}
	}

	// -- boilerplate code --

	private static final long serialVersionUID = 1L;

	ProcessBusiness processBusiness;

	public ProcessBusiness getProcessBusiness() {
		return processBusiness;
	}

	@EJB(name = "ejb/ProcessBusinessBean")
	public void setProcessBusiness(ProcessBusiness processBusiness) {
		this.processBusiness = processBusiness;
	}

	public void ejbRemove() throws EJBException {
		// empty
	}

	public void setMessageDrivenContext(MessageDrivenContext arg0)
			throws EJBException {
		// empty
	}

	public void ejbCreate() throws CreateException {
		// empty
	}
}
